<?php
/**
 * PublicController.php
 * @author 瀚海浪亭
 * @email  1171672036@qq.com
 * @date   2021/4/19
 */

namespace app\api\controller;

use app\common\exception\RequestException;
use app\common\service\ImageCaptchaService;
use app\api\validate\PublicValidate;
use app\common\model\UserModel;
use think\facade\Config;
use think\facade\Request;
use Tools\Responses;

class PublicController
{
    /**
     * 登录
     *
     * @return Json
     */
    public function login()
    {
        $params             = [];
        $params['username'] = Request::post('username/s');
        $params['password'] = Request::post('password/s');
        $params['time']     = time();
        $params['ip']       = Request::ip();

        // 检验用户名和密码
        $validate = new PublicValidate();
        $vResult  = $validate->scene(__FUNCTION__)->check($params);
        if (!$vResult) {
            throw new RequestException(400, $validate->getError());
        }

        $user = UserModel::where('username', '=', $params['username'])->find();
        if (!$user) {
            return Responses::data(404, '用户不存在');
        }
        if (md5_plus($params['password']) != $user['password']) {
            return Responses::data(500, '用户名或者密码错误');
        }

        // 更新用户的 ip 和登录时间
        $update = [
            'last_login_ip'   => $params['ip'],
            'last_login_time' => $params['time']
        ];
        UserModel::where('id', '=', $user['id'])->update($update);

        $data          = $user;
        $data['token'] = self::createToken($user['id']);

        unset($data['password']);
        unset($data['create_time']);
        unset($data['update_time']);
        unset($data['delete_time']);

        return Responses::data(200, '登录成功', $data);
    }

    /**
     * 注册
     *
     * @return Json
     */
    public function register()
    {
        $params             = [];
        $params['username'] = Request::post('username', '', 'trim,strip_tags,htmlspecialchars');
        $params['password'] = Request::post('password');
        $params['status']   = 1;

        $validate = new PublicValidate();
        $vResult  = $validate->scene(__FUNCTION__)->check($params);
        if (!$vResult) {
            return Responses::data(400, $validate->getError());
        }

        // 将密码加密
        $params['password'] = md5_plus($params['password']);

        try {
            $info = UserModel::create($params);
            if (!$info) {
                return Responses::data(500, '注册失败');
            }

            return Responses::data(200, '注册成功');
        } catch (\Exception $e) {
            return Responses::data(500, $e->getMessage());
        }
    }

    /**
     * 图形验证码
     *
     * @return Json
     */
    public function image()
    {
        $imageCaptchaService = new ImageCaptchaService();
        $data                = $imageCaptchaService->verify();
        return Responses::data(200, '请求成功', $data);
    }

    /**
     * 短信验证码
     *
     * @return Json
     */
    public function sms()
    {
        return Responses::data(200, '短信验证码发送成功', '短信验证码');
    }

    /**
     * 邮箱验证码
     *
     * @return Json
     */
    public function email()
    {
        return Responses::data(200, '邮箱验证码发送成功');
    }

    /**
     * 创建 token
     * @param int $user_id 用户 id
     * @param int $expire_time 过期时间
     * @return string
     */
    public static function createToken($user_id, $expire_time = 86400)
    {
        $key  = Config::get('api.domain');
        $data = [
            'user_id'     => $user_id,
            'create_time' => time(),
            'expire_time' => empty($expire_time) ? 0 : time() + $expire_time
        ];

        $token = encrypt(json_encode($data), $key);

        return $token;
    }
}